/**
 * 聊天对象
 * Created by yanyuan on 2014/11/21.
 */
angular.module('myApp.ChatHandler', ['myApp.CacheServices', 'myApp.ChatModel', 'myApp.GroupHandler', 'myApp.ChatHandler', 'myApp.Manager'])
    .factory('ChatHandler', ['$rootScope', 'LocalCacheService', 'Chat' , 'GroupHandler', 'ContactHandler', 'MessageManager', function ($rootScope, LocalCacheService, Chat, GroupHandler, ContactHandler, MessageManager) {
        var chatsMap = $rootScope.chatsMap = {};
        var init = function(){
            getChatsInit();
        }

        var addChat = function (chat) {
            if(!checkValid(chat)) return;
            var chatObj = null;
            if(chat.isGroup){
                var group = GroupHandler.getGroupByIdentifier(chat.identifier);
            	chat.userCount = group == null ? null : group.userCount;
            }
            if (chatsMap[chat.identifier] == null) {
                chatsMap[chat.identifier] = chat;
                if(checkUnreadMsg(chat)){//未读消息处理
                    chatsMap[chat.identifier].unreadMessages = 1;
                    $rootScope.allUnreadMessages++;
                }
                chatObj = angular.copy(chatsMap[chat.identifier]);
            } else {
                chatsMap[chat.identifier].name = chat.name;
            	chatsMap[chat.identifier].avatar = chat.avatar;
                chatsMap[chat.identifier].messageContent = chat.messageContent;
                chatsMap[chat.identifier].messageTime = chat.messageTime;
                chatsMap[chat.identifier].operaterTime = chat.operaterTime;
               if(checkUnreadMsg(chat)){//未读消息处理
                    chatsMap[chat.identifier].unreadMessages++;
                    $rootScope.allUnreadMessages++;
                }
                chatObj = angular.copy(chatsMap[chat.identifier]);
            }
            LocalCacheService.set('chats', JSON.stringify(saveChatFormat(chatsMap)));
            return chatObj;
        };

        function checkValid(chat){
            if(chat.isGroup){
                return GroupHandler.groupIsExist(chat.identifier);
            }else{
                return ContactHandler.contactIsExist(chat.identifier);
            }
        }

        function checkUnreadMsg(chat){
            if(chat.messageContent == null || chat.messageContent.trim().length == 0){
                return false;
            }
            if(chat.isme == $rootScope.user.identifier){
                return false
            }
            if($rootScope.currentChatObj && chat.identifier == $rootScope.currentChatObj.identifier){
                return false;
            }
            return true;
        }

        var getChatsInit = function(){
            $rootScope.allUnreadMessages = 0;
            if(LocalCacheService.get('chats')){
                var cacheChatsMap = JSON.parse(LocalCacheService.get('chats'));
                for(var key in  cacheChatsMap){
                    var chat = cacheChatsMap[key];
                    var differDays = (new Date(util.getServerTime()).getTime() - new Date(chat.operaterTime).getTime())/1000/60/60/24;
                    if(differDays > 7){//加载7天内联系人
                        return;
                    }
                    addChat(chat);//过滤无效群聊,联系人
                }
            }
        }

        var saveChatFormat = function (chatsMap) {
            var newChatsMap = {};
            for (var key in chatsMap) {
                var chat = angular.copy(chatsMap[key]);
                var differDays = (new Date(util.getServerTime()).getTime() - new Date(chat.operaterTime).getTime()) / 1000 / 60 / 60 / 24;
                if (differDays < 7) {//保存7天内联系人
                    chat.messageContent = null;
                    chat.messageTime = null;
                    chat.unreadMessages = 0;
                    chat.sendState = 1;
                    newChatsMap[key] = chat;
                }
            }
            return newChatsMap;
        }

        var updateChat = function(chat){
            if(chat.identifier == null || chatsMap[chat.identifier] == null){
                return;
            }
            var existChat = chatsMap[chat.identifier];
            if(chat.name){
                existChat.name = chat.name;
            }
            if(chat.userCount){
                existChat.userCount = chat.userCount;
            }
            if(chat.messageContent){
                existChat.messageContent = chat.messageContent;
            }
            if(chat.messageTime){
                existChat.messageTime = chat.messageTime;
            }
            if(chat.operaterTime){
                existChat.operaterTime = chat.operaterTime;
            }
            LocalCacheService.set('chats', JSON.stringify(saveChatFormat(chatsMap)));
        }

        var getChar = function (identifier) {
            return chatsMap[identifier];
        }

        var getAllChars = function () {
            return chatsMap;
        }

        var cleanUnreadMessages = function (identifier) {
            chatsMap[identifier].unreadMessages = 0;
        }

        var message2Chat = function(message){
            var chat = Chat.build();
            if(message.send){
                messageSend2Chat(message, chat);
            }else{
                messageReceive2Chat(message, chat);
            }
            chat.isme = message.isme;
            chat.isGroup = message.group;
            chat.messageContent = message.content;
            chat.messageTime = new Date(message.timestamp);
            chat.operaterTime = message.timestamp;
            return chat;
        }

        var messageSend2Chat = function(message, chat){
            chat.identifier = message.to;
            if(message.group){
                chat.name = GroupHandler.getGroupByIdentifier(chat.identifier).name;
            }else{
                chat.name = ContactHandler.getContact(chat.identifier).name;
                chat.avatar = ContactHandler.getContact(chat.identifier).avatar;
            }
        }

        var messageReceive2Chat = function(message, chat){
            if(message.group){
                chat.identifier = message.to;
                chat.name = GroupHandler.getGroupByIdentifier(chat.identifier).name;
            }else{
                chat.identifier = ContactHandler.getContact(message.from).identifier;
                chat.name = ContactHandler.getContact(message.from).name;
                chat.avatar = ContactHandler.getContact(message.from).avatar;
            }
        };

        var groupCommandMessage2Chat = function(message){//群组命令消息
            var chat = Chat.build();
            chat.identifier = message.groupId;
            chat.name = GroupHandler.getGroupByIdentifier(chat.identifier).name;
            chat.isGroup = true;
            var date = util.getServerTime();
            chat.messageTime = date;
            chat.operaterTime = new Date(date).getTime();
            chat.messageContent = message.content;
            return chat;
        }

        var refreshChat = function(){
            for (var key in chatsMap) {
                var chat = chatsMap[key];
                if(chat.isGroup){
                    continue;
                }
                chat.identifier = ContactHandler.getContact(key).identifier;
                chat.name = ContactHandler.getContact(key).name;
                chat.avatar = ContactHandler.getContact(key).avatar;
            }
            $rootScope.chatsMap = chatsMap;
        }

        return{
            init : init,
            addChat : addChat,
            getChat : getChar,
            getAllChats : getAllChars,
            updateChat : updateChat,
            cleanUnreadMessages: cleanUnreadMessages,
            message2Chat : message2Chat,
            groupCommandMessage2Chat : groupCommandMessage2Chat,
            refreshChat : refreshChat
        }
    }]);